package br.com.massai.model.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.NoResultException;

import br.com.massai.model.entity.CategoryLevel;
import br.com.massai.model.entity.ServiceItem;
import br.com.massai.model.exceptions.SystemException;

@Stateless
public class ServiceItemDAO extends GenericDAO<ServiceItem> implements ServiceItemRepository {

	private static final long serialVersionUID = 7216448219609252170L;
	private static final String QUERY_AUTOCOMPLETE = "SELECT s FROM ServiceItem s WHERE LOWER(s.description) LIKE LOWER(:description) AND s.flagFixed =:flagFixed";
	
	public ServiceItemDAO() {
		super(ServiceItem.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ServiceItem> autocompleteMethod(String str) throws SystemException {
		List<ServiceItem> resultList = new ArrayList<>();
		try {
			resultList = em.createQuery(QUERY_AUTOCOMPLETE)
					.setParameter("description", "%"+str+"%")
					.setParameter("flagFixed", false)
					.getResultList();

		} catch (Exception e) {
			e.printStackTrace();
			return new ArrayList<>(); 
		}
		return resultList;
	}

	@Override
	public Number getNextNumber(CategoryLevel categoryLevel) throws SystemException {
		Number result = 0;

		try {
			result = (Number) em.createNativeQuery("SELECT MAX(CAST(level_service AS INTEGER)) FROM service_item WHERE category_level_id = :category").setParameter("category", categoryLevel.getId()).getSingleResult();
			if(result == null) result = 0;

		} catch (NoResultException e) {
			e.printStackTrace();
		}
		return result.intValue() + 1;
	}
}